//浏览器语言
chrome.storage.sync.get(null, function(items) {
	listen(items);
});

chrome.storage.onChanged.addListener(function(changes, namespace) {
	document.removeEventListener("mouseup", mouseup);
	document.removeEventListener("keyup", keyup);
	listen(changes);
});
//事件监听
function listen(data){
	info.curData = data;
	if(data["way_option_item"] == 1){
		document.addEventListener("mouseup", mouseup);
	}else{
		document.addEventListener("keyup", keyup);
	}
}
function mouseup() {
	translate(info.curData["te_option_item"]);
}
function keyup(event) {
	if(event.keyCode==17 && !info.otherKey) {
		mouseup();
	}
}
document.addEventListener("keydown", function(event){
	if(event.keyCode==17) {
		info.otherKey = false;
	}else{
		info.otherKey = true;
	}
});
//检测语言
function checkLang(a, b){
	var lk = function(a, b, c) {
		if(a) {
			var d = a.innerText || a.textContent || "";
			d = decodeURIComponent(encodeURIComponent(d.trim()));
			chrome.i18n.detectLanguage(d, function(d) {
				d.isReliable ? c(d.languages[0].language) : 0 < b ? lk(a.parentNode,b - 1, c) : c("")
			})
		} else {
			c("");
		}
	};
	var c = a.toString().trim();
	c = decodeURIComponent(encodeURIComponent(c));
	chrome.i18n.detectLanguage(c, function(result) {
		var d = "";
		if(result.isReliable)	return d = result.languages[0].language, b(d);//获得语言
		else{
			lk(a.anchorNode, 3, function(a) {b(a)});
		}
	});
}

chrome.i18n.getAcceptLanguages(function(languageArray){
    info.languageArray = languageArray;
});
var info = {
	lang: chrome.i18n.getUILanguage ? chrome.i18n.getUILanguage() : "en",
	languageArray: [],
	otherKey: false,
	curData: {},
	lastText: "",
	jQueryPre: ("1.10.2" + Math.random()).replace(/\D/g, ""),
	timestamp : (new Date()).getTime(),
	offset : 10
}
//过滤数据
function filter(src){
	if(src.trim() == "" || info.lastText == src){
		return null;
	}
	info.lastText = src;
	return src;
}
function getSelectionRange() {
	var sel = document.selection,
		range = null;
	var width = 0,
		height = 0,
		left = 0,
		top = 0;
	if(sel) {
		if(sel.type != "Control") {
			range = sel.createRange();
		}
	} else if(window.getSelection) {
		sel = window.getSelection();
		if(sel.rangeCount) {
			range = sel.getRangeAt(0).cloneRange();
		}
	}
	return range;
}

function getSelectionDimensions() {
	var range = getSelectionRange();
	if(!range)
		return null;
	var sel = document.selection;
	var width = 0,
		height = 0,
		left = 0,
		top = 0;
	if(sel) {
		if(sel.type != "Control") {
			width = range.boundingWidth;
			height = range.boundingHeight;
			left = range.boundingLeft;
			top = range.boundingTop;
		}
	} else if(window.getSelection) {
		sel = window.getSelection();
		if(sel.rangeCount) {
			if(range.getBoundingClientRect) {
				var rect = range.getBoundingClientRect();
				width = rect.right - rect.left;
				height = rect.bottom - rect.top;
				left = rect.left;
				top = rect.top;
			}
		}
	}
	return {width: width,height: height,left: left,top: top};
}

function calcPosition(){
	var dimension = getSelectionDimensions();
	var res = {};
	res.rect = {
		x1: dimension.left,//左上
		y1: dimension.top,
		x2: dimension.left + dimension.width,//右下
		y2: dimension.top + dimension.height,
		height: dimension.height,
		width: dimension.width
	};
	res.arrowLeft = 10;
	res.scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
	res.scrollLeft = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft;
	res.top = res.scrollTop + res.rect.y2 + 8;
	res.left = res.scrollLeft + (res.rect.x1 + res.rect.x2) / 2 - res.arrowLeft - 8;
	//默认翻译窗口在下方
	if(window.innerHeight + res.scrollTop >= document.body.scrollHeight-50){  //滑动到底部的判断
		res.top = undefined;
	}
	return res;
}


function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
                return obj;
            }else{
                return null;
            }
        } catch(e) {
            return null;
        }
    }
}
//请求数据
function translate(type) {
	var select = window.getSelection();
	var src = select.toString().trim();
	if(filter(src) == null) return;
	var position = calcPosition();
	var url = "";
	if(type == 1) { //百度
		url = "https://sp1.baidu.com/5b11fzupBgM18t7jm9iCKT-xh_/sensearch/selecttext";
		url += "?cb=jQuery" + info.jQueryPre + "_" + info.timestamp;
		url += "&q=" + src;
		url += "&_=" + (parseInt(info.timestamp) + info.offset++);
		httpRequest(url, function(responseText) {
			createPop(analyzeBaidu(responseText), position);
		});
	} else { //默认google
		//计算语言
		checkLang(select, function(d) {
			var qh = function(a) {
					a = String(a).toLowerCase().replace("_", "-");
					if("zh-cn" == a) return "zh-CN";
					if("zh-tw" == a) return "zh-TW";
					var b = a.indexOf("-");
					a = 0 <= b ? a.substring(0, b) : a;
					return "zh" == a ? "zh-CN" : a
				},
				Rh = function(a) {
					if("" != a.c) a = a.c;
					else a: {
						for(var b = 0; b < a.h.length; b++) {
							var c = qh(a.h[b]);
							if(a.b[c]) {
								a = c;
								break a
							}
						}
						a = "en"
					}
					return a
				},
				Uh = function(a) {
					var b = function(a) {
						this.h = info.languageArray;
						this.c = "";
						this.a = "1";
						this.i = !0;
						this.b = [];
						this.j = [];
						this.u = !!a;
					};
					a = qh(a);
					return a == Rh(b) ? !0 : !1
				};
			if(!Uh(d)) {
				if("zh" == d || "zh-Hant" == d) d = "zh-CN";
				var Vb = function(a) {
						return function() {
							return a
						}
					},
					Wb = function(a, b) {
						for(var c = 0; c < b.length - 2; c += 3) {
							var d = b.charAt(c + 2);
							d = "a" <= d ? d.charCodeAt(0) - 87 : Number(d);
							d = "+" == b.charAt(c + 1) ? a >>> d : a << d;
							a = "+" == b.charAt(c) ? a + d & 4294967295 : a ^ d
						}
						return a
					},
					Xb = null,
					Yb = function(a) {
						if(null !== Xb) var b = Xb;
						else {
							b = Vb(String.fromCharCode(84));
							var c = Vb(String.fromCharCode(75));
							b = [b(), b()];
							b[1] = c();
							b = (Xb = window[b.join(c())] || "") || ""
						}
						var d = Vb(String.fromCharCode(116));
						c = Vb(String.fromCharCode(107));
						d = [d(), d()];
						d[1] = c();
						c = "&" + d.join("") +
							"=";
						d = b.split(".");
						b = Number(d[0]) || 0;
						for(var e = [], f = 0, g = 0; g < a.length; g++) {
							var k = a.charCodeAt(g);
							128 > k ? e[f++] = k : (2048 > k ? e[f++] = k >> 6 | 192 : (55296 == (k & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (k = 65536 + ((k & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = k >> 18 | 240, e[f++] = k >> 12 & 63 | 128) : e[f++] = k >> 12 | 224, e[f++] = k >> 6 & 63 | 128), e[f++] = k & 63 | 128)
						}
						a = b;
						for(f = 0; f < e.length; f++) a += e[f], a = Wb(a, "+-a^+6");
						a = Wb(a, "+-3^+b+-f");
						a ^= Number(d[1]) || 0;
						0 > a && (a = (a & 2147483647) + 2147483648);
						a %= 1E6;
						return c + (a.toString() + "." +
							(a ^ b))
					};

				url = "https://translate.googleapis.com/translate_a/single";
				url += "?client=gtx";
				d = d ? d : "auto";
				url += "&sl=" + d;
				url += "&tl=" + info.languageArray[0];
				url += "&hl=" + info.lang;
				if(d.indexOf(info.lang)!=-1 || info.lang.indexOf(d)!=-1){
					return ;
				}
				url += "&dt=t";
				url += "&dt=bd";
				url += "&dj=1";
				url += "&source=" + (info.curData["way_option_item"]==0?"icon":"bubble");
				url += "&tk=" + Yb(src);
				url += "&q=" + src;
				httpRequest(url, function(responseText) {
					createPop(analyzeGoogle(responseText), position);
				});
			}
		});
		
	}
}

/*
data格式
{
	success: true,
	result:[
		"pre": "n.",
		"cont": "你好"
	]
}
 */
//解析百度返回数据
function analyzeBaidu(src){
	let start = src.indexOf("(");
	let end = src.lastIndexOf(")");
	src = JSON.parse(unescape(src.substring(start+1, end).replace(/\\/g,'%')));
	var res = {};
	if(src.errno == 0){
		res.success = true;
		res.result = src.data.result;
		res.type = 1;
		res.from = src.data.form;
		res.to = src.data.to;
	}else{
		res.success = false;
	}
	return res;
}
//解析google数据
function analyzeGoogle(src){
	var val = JSON.parse(src);
	var res = {};
	res.success = true;
	var t;
	if(val.dict){
		res.result = [];
		for(t = 0, l=val.dict.length; t<l; t++){
			var e = {};
			e["pre"] = val.dict[t].pos;
			e["cont"] = val.dict[t].terms.join(";&nbsp;");
			res.result.push(e);
		}
	}else{
		res.result = "";
		for(t = 0, l=val.sentences.length; t<l; t++){
			res.result +=val.sentences[t].trans + "<br>";
		}
	}
	res.from = val.src;
	res.to = info.lang;
	res.type = 0;
	return res;
}

/*
data格式
{
	success: true | false,
	type: 0 | 1,
	from: "en",
	to: "zh",
	result:[
		"pre": "n.",
		"cont": "你好"
	]
}
 */
function createPop(data, position){
	if(data.success == false){
		return ;
	}
	var divEle = document.querySelector("#trans-tips-container");
	var bodyEle = document.querySelector("body");
	if(divEle != null){
		divEle.remove();
	}
	divEle = document.createElement("div");
	var divHtml = "";
	divEle.id = "trans-tips-container";
	divHtml += '<div class="trans-tip-con" style="display:block;">';
	divHtml += '<div><div class="translateContent"><p align="left" style="margin:0 8px">';
	var translateContent = "";
	if(typeof(data.result) == "string"){
		translateContent += '<span style="color:#999">译：</span>' + data.result;
	}else{
		if(data.type == 1){//baidu
			for(var t = 0,len = data.result.length; t < len; t++){
			    translateContent += (data.result[t].pre==null ? "" : '<span style="color:#999">' + data.result[t].pre  + '</span>&nbsp;') + data.result[t].cont+ "<br>";
			}
		}else if(data.type == 0){//google
			for(var t = 0,len = data.result.length; t < len; t++){
			    translateContent += (data.result[t].pre==null ? "" : '<span style="color:#999">[' + data.result[t].pre  + ']</span>&nbsp;') + data.result[t].cont+ "<br>";
			}
		}else{
			return ;
		}
	}
	divHtml += translateContent;
	divHtml += '</p></div></div><div class="trans-tip-arrow" style="background: red;"><em></em><ins></ins></div></div>';
	divEle.innerHTML = divHtml;
	bodyEle.appendChild(divEle);
	var transTipConEle = divEle.querySelector(".trans-tip-con");
	//	重新计算top
	if(position.top!=undefined){
		transTipConEle.style.top = position.top + "px";
	}else{
		transTipConEle.style.top = (position.scrollTop + position.rect.y1 - transTipConEle.offsetHeight - 8) + "px";
		divEle.querySelector(".trans-tip-arrow").classList.add("trans-tip-arrow-down");
	}
	var contentLeft = document.body.clientWidth + position.scrollLeft;
	transTipConEle.querySelector(".translateContent p").style.width = transTipConEle.offsetWidth;
	var offset = transTipConEle.offsetWidth + position.left - contentLeft;
	if(offset > 0){
		position.left = contentLeft - transTipConEle.offsetWidth;
		position.arrowLeft = position.scrollLeft + (position.rect.x1+position.rect.x2) / 2-8 - position.left;
	}
	transTipConEle.style.left = position.left + "px";
	divEle.querySelector(".trans-tip-arrow").style.left = position.arrowLeft + "px";
	transTipConEle.style.display = "block";
	bodyEle.addEventListener("mousedown", reoveArea);
}
function reoveArea(e){
	divEle = document.querySelector("#trans-tips-container");
	var target = e.srcElement ? e.srcElement : e.target;
	if(!divEle.contains(target)){
		divEle.remove();
		info.lastText = "";
		document.querySelector("body").removeEventListener("mousedown", reoveArea);
	}
}
function httpRequest(url, callback) {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", url, true);
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			callback(xhr.responseText);
		}
	}
	xhr.send();
}